import React, { useState, useRef, useEffect } from 'react'
import { Divider, Skeleton, Input, Button, Avatar, Card } from 'antd'
import { SendOutlined, UserOutlined, OpenAIOutlined } from '@ant-design/icons'
import { MarkdownRender, Panel } from '@/base/components'
import { userService } from '@/domain/user'

const { TextArea } = Input

interface Message {
  id: string
  content: string
  isUser: boolean
  timestamp: Date
  loading?: boolean
}

const AiAnswerPage: React.FC = () => {
  const [messages, setMessages] = useState<Message[]>([
    {
      id: '1',
      content: '你好！我是YH-NOTE助手，有什么可以帮您的吗？',
      isUser: false,
      timestamp: new Date(),
    },
  ])
  const [inputValue, setInputValue] = useState('')
  const [loading, setLoading] = useState(false)
  const messagesEndRef = useRef<HTMLDivElement>(null)

  // 滚动到底部
  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' })
  }

  useEffect(() => {
    scrollToBottom()
  }, [messages])

  // 调用后端 AI 接口
  const getAIResponse = async (userMessage: string) => {
    setLoading(true)
    // 添加加载中的消息
    setMessages((prev) => [
      ...prev,
      {
        id: `loading-${Date.now()}`,
        content: '',
        isUser: false,
        timestamp: new Date(),
        loading: true,
      },
    ])

    try {
      // 调用 useAI 返回的函数
      const aiResponse = await userService.AIUse({ prompt: userMessage })
      // 更新消息列表
      setMessages((prev) => {
        const newMessages = prev.filter((msg) => !msg.loading)
        return [
          ...newMessages,
          {
            id: `${Date.now()}`,
            content: aiResponse.data,
            isUser: false,
            timestamp: new Date(),
          },
        ]
      })
    } catch (error) {
      console.error('API调用错误:', error)
      // 添加错误消息
      setMessages((prev) => {
        const newMessages = prev.filter((msg) => !msg.loading)
        return [
          ...newMessages,
          {
            id: `error-${Date.now()}`,
            content: '请求失败，请稍后再试',
            isUser: false,
            timestamp: new Date(),
          },
        ]
      })
    } finally {
      setLoading(false)
    }
  }

  const handleSend = () => {
    if (!inputValue.trim()) return

    // 添加用户消息
    const newUserMessage: Message = {
      id: `${Date.now()}`,
      content: inputValue,
      isUser: true,
      timestamp: new Date(),
    }

    setMessages((prev) => [...prev, newUserMessage])

    // 调用后端 AI 接口
    getAIResponse(inputValue)

    setInputValue('')
  }

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault()
      handleSend()
    }
  }

  return (
    <div className="flex justify-center">
      <div className="w-[1000px]">
        <Panel>
          <div className="text-neutral-1000 text-sm font-semibold">AI帮助</div>
          <Divider />
          <div className="flex h-[600px] flex-col">
            {/* 消息区域 */}
            <div className="mb-4 flex-1 overflow-y-auto rounded-lg bg-gray-50 p-4">
              {messages.map((message) => (
                <div
                  key={message.id}
                  className={`mb-6 flex ${message.isUser ? 'justify-end' : 'justify-start'}`}
                >
                  <div className="flex max-w-[85%]">
                    {!message.isUser && (
                      <Avatar
                        className="mr-3 mt-1"
                        icon={<OpenAIOutlined />}
                        style={{ backgroundColor: '#1890ff' }}
                      />
                    )}

                    <Card
                      bordered={false}
                      className={`${
                        message.isUser
                          ? 'border-blue-100 bg-blue-50'
                          : 'border-gray-200 bg-white'
                      } rounded-2xl shadow-sm`}
                      bodyStyle={{ padding: '12px 16px' }}
                    >
                      {message.loading ? (
                        <Skeleton active paragraph={{ rows: 2 }} />
                      ) : (
                        <div className="w-[700px] whitespace-pre-wrap text-base">
                          <MarkdownRender markdown={message?.content ?? ''} />
                        </div>
                      )}
                      <div
                        className={`mt-2 text-xs ${message.isUser ? 'text-right' : 'text-left'} text-gray-400`}
                      >
                        {message.timestamp.toLocaleTimeString([], {
                          hour: '2-digit',
                          minute: '2-digit',
                        })}
                      </div>
                    </Card>

                    {message.isUser && (
                      <Avatar
                        className="ml-3 mt-1"
                        icon={<UserOutlined />}
                        style={{ backgroundColor: '#f56a00' }}
                      />
                    )}
                  </div>
                </div>
              ))}
              <div ref={messagesEndRef} />
            </div>

            {/* 输入区域 */}
            <div className="border-t pt-4">
              <div className="flex items-end">
                <TextArea
                  value={inputValue}
                  onChange={(e) => setInputValue(e.target.value)}
                  onPressEnter={handleKeyPress}
                  placeholder="输入您的问题..."
                  autoSize={{ minRows: 2, maxRows: 6 }}
                  className="mr-3 flex-1"
                  disabled={loading}
                />
                <Button
                  type="primary"
                  icon={<SendOutlined />}
                  onClick={handleSend}
                  loading={loading}
                  disabled={!inputValue.trim()}
                  className="h-[56px]"
                >
                  发送
                </Button>
              </div>
              <div className="mt-2 text-xs text-gray-400">
                按Enter发送，Shift+Enter换行
              </div>
            </div>
          </div>
        </Panel>
      </div>
    </div>
  )
}

export default AiAnswerPage
